package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baidubce.qianfan.util.CollUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.DeviceInfo;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.BedVo;
import com.zzyl.nursing.vo.RoomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;

    //缓存依赖注入
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        //清除缓存
        removeCache();
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        //清除缓存
        removeCache();
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    /**
     * 清除缓存
     */
    public void removeCache(){
        redisTemplate.delete(CacheConstants.ROOM_KEY);
    }

    /**
     * 根据房间id查询房间数据(楼层、房间、价格)
     *
     * @param id
     * @return
     */
    @Override
    public RoomVo getOneRoomInfo(Long id) {
        // 通过缓存查询房间数据
        List<String> stringList = redisTemplate.opsForList().range(CacheConstants.ROOM_KEY, 0, -1);
        RoomVo roomVo = null;
        if (!CollectionUtils.isEmpty(stringList)) {
            // 通过房间id获取房间数据
            List<RoomVo> roomVoList = stringList.stream()
                    .map(x -> JSON.parseObject(x, RoomVo.class))
                    .collect(Collectors.toList());
            roomVo = roomVoList.stream()
                    .filter(x -> x.getRoomId() != null && Long.valueOf(x.getRoomId()).equals(id)) // 确保ID非空
                    .findFirst()
                    .orElse(null);
        }

        // 直接从数据库中获取数据
        if (roomVo == null) {
            roomVo = roomMapper.getOneRoomInfo(id);
            if (roomVo != null) { // 确保从数据库获取的数据非空后再写入缓存
                redisTemplate.opsForList().leftPush(CacheConstants.ROOM_KEY, JSON.toJSONString(roomVo));
            } else {
                return new RoomVo(); // 或者考虑抛出异常或返回null，取决于业务需求
            }
        }
        return roomVo;
    }


    /**
     * 获取房间中的智能设备及数据
     *
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
        //1.调用mapper获取前三层数据
        List<RoomVo> roomVoList = roomMapper.getRoomsWithDeviceByFloorId(floorId);

        if (CollectionUtils.isEmpty(roomVoList)){
            return Collections.emptyList();//返回空数据列表
        }
        //2.使用缓存获取并存入设备数据
        roomVoList.forEach(r->{
            //获取房间下的设备列表数据
            List<DeviceInfo> rdDeviceInfoList = r.getDeviceVos();
            if (CollUtil.isNotEmpty(rdDeviceInfoList)){
                rdDeviceInfoList.forEach(rd->{
                    //根据设备iotid查询对应的设别数据列表
                    String rdDeviceInfoListJSON = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, rd.getIotId()).toString();
                    if (StringUtils.isNotBlank(rdDeviceInfoListJSON)){
                        List<DeviceData> rdDeviceDataList = JSONUtil.toList(rdDeviceInfoListJSON, DeviceData.class);
                        //填充
                        rd.setDeviceDataVos(rdDeviceDataList);
                    }
                });
            }

            //获取房间下的床位的设备列表数据
            List<BedVo> bedVoList = r.getBedVoList();
            if (!CollectionUtils.isEmpty(bedVoList)){
                bedVoList.forEach(b->{
                    //获取床位下的列表设备数据
                    List<DeviceInfo> bdDeviceInfoList = b.getDeviceVos();
                    if (CollUtil.isNotEmpty(bdDeviceInfoList)){
                        bdDeviceInfoList.forEach(bd->{
                            //根据设备iotid查询对应的设别数据列表
                            String bdDeviceInfoListJSON = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, bd.getIotId()).toString();
                            if (StringUtils.isNotBlank(bdDeviceInfoListJSON)){
                                List<DeviceData> bdDeviceDataList = JSONUtil.toList(bdDeviceInfoListJSON, DeviceData.class);
                                bd.setDeviceDataVos(bdDeviceDataList);


                            }
                        });
                    }
                });
            }
        });

        return roomVoList;
    }
}
